﻿
using System;
using System.Net.Sockets;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading;

namespace s7nck
{
    class Class1
    {

        public static byte[]  receibeMessage(Socket socketSend,int length)
        {
            
                StateObject state = new StateObject(length);
                state.workSocket = socketSend;
                ManualResetEvent event2 = new ManualResetEvent(false);
                state.WaitDone = event2;
            try
            {
                if (socketSend != null && socketSend.Connected)
                {
                    socketSend.BeginReceive(state.buffer, 0, length, SocketFlags.None, new AsyncCallback(Class1.Read_Callback), state);

                }

            }
            catch (Exception ex)
            {

                LogHelper.WriteLog(ex.Message, ex);

            }


            event2.WaitOne();
                // event2.Close();
                // socketSend.Close();
                /*把有值的数组复制出来*/


                return state.buffer;
           


        }

    public static  void Read_Callback(IAsyncResult ar)
    {
      

           
            StateObject so = (StateObject)ar.AsyncState;
       try
         {
           if (so != null)
           {
                Socket s = so.workSocket;
                    int read = 0;

                    if (s.Connected)
                    {
                         read = s.EndReceive(ar);

                    }
                    

                    if (read <= 0)
                    {
                        
                        so.WaitDone.Set();
                    }
                    else
                    {
                        // so.WaitDone.Set();
                        so.AlreadyDealLength += read;
                        if (so.AlreadyDealLength < so.BUFFER_SIZE)
                        {
                            if (s.Connected)
                            {
                                s.BeginReceive(so.buffer, 0, so.BUFFER_SIZE, SocketFlags.None, new AsyncCallback(Read_Callback), so);

                            }
                            else
                            {
                                so.WaitDone.Set();
                            }





                        }
                        else
                        {
                            so.WaitDone.Set();
                        }
                    }
                 

                



            }
        }
        catch (Exception ex)
          {

                LogHelper.WriteLog(ex.Message, ex);
                so.WaitDone.Set();

            }

        }
           
    }
}
